const http = require('http')
const fs = require('fs')

let tableData = require('./data.json')

const funMap = {
    // 子模块
    SubModule: {
        getList: async (postData) => {
            return JSON.stringify(tableData)
        },
        getItem: async (postData) => {
            for (let i in tableData) {
                if (tableData[i].key === postData.key) {
                    return JSON.stringify(tableData[i])
                }
            }
            return '未查到子模块'
        },
        // 添加单个子模块
        addItem: async (postData) => {
            let id = null
            if (tableData.length) {
                id = tableData[tableData.length - 1].id + 1
            } else {
                id = 1
            }
            tableData.push({
                ...postData,
                id: id
            })
            fs.writeFileSync('./data.json', JSON.stringify(tableData))
            return '添加成功！'
        },
        // 修改单个子模块
        editItem: async (postData) => {
            for (let i in tableData) {
                if (tableData[i].id === postData.id) {
                    tableData[i] = postData
                    fs.writeFileSync('./data.json', JSON.stringify(tableData))
                    return '修改成功！'
                }
            }
        },
        delItem: async (postData) => {
            for (let i in tableData) {
                if (tableData[i].id === postData.id) {
                    tableData.splice(+i, 1)
                    fs.writeFileSync('./data.json', JSON.stringify(tableData))
                    return '删除成功！'
                }
            }
        }
    }
}

let server = http.createServer((req, res) => {
    //设置跨域
    //设置允许来自哪里的跨域访问:'*'表示所有的跨域
    res.setHeader("Access-Control-Allow-Origin", "*");
    //设置允许跨域访问的方式：服务器接收哪些方式的跨域访问
    res.setHeader("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE,OPTIONS")
    //设置请求头中允许携带的参数
    res.setHeader("Access-Control-Allow-Headers", "Content-Type,request-origin");
    if (req.url != '/favicon.ico') {
        //1.设置响应信息的格式和字符集
        res.setHeader('Content-Type', 'text/html;charset=utf8')
        let postData = ''
        console.log('1',req.url)
        let funKeyList = req.url.split('/')
        console.log('2',funKeyList)
        funKeyList.splice(0, 1)
        console.log('3',funKeyList)
        let fun = funMap
        for (let i in funKeyList) {
            fun = fun[funKeyList[i]]
        }
        try {
            req.on('data', chunk => {
                postData += chunk.toString()
            })
            req.on('end', async () => {
                if (postData) postData = JSON.parse(postData)
                let resData = await fun(postData)
                res.end(resData)
            })

        } catch (error) {
            console.log('错误！', error)
            res.end(error.toString)
        }
    }
})

// 启动server监听
server.listen(9000, "127.0.0.1", () => {
    console.log('服务器已启动，运行在9000端口上...')
})